package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("PictureService")
@Transactional

public class PictureServiceImpl extends CmiEmaService implements PictureService {
	public PictureServiceImpl() {
	}

	@Transactional
	public Picture savePicture(Picture picture) {

		if (picture.getId() == null) {
			Event event = eventDAO.findEventById(picture.getEvent().getId());
			Food food = foodDAO.findFoodById(picture.getFood().getId());

			Picture existingPicture = pictureDAO.findPictureByPhysicalPrimaryKey(picture.getName(), picture.getPath());

			picture.setEvent(event);
			picture.setFood(food);

			if (isEquals(picture, existingPicture)) {
				return existingPicture;
			}

			picture = pictureDAO.store(picture);
			pictureDAO.flush();

		} else {
			Picture existingPicture = pictureDAO.findPictureByPrimaryKey(picture.getId());

			picture = pictureDAO.store(picture);
			pictureDAO.flush();
		}

		return picture;
	}

	public void deletePicture(Picture picture) {
		pictureDAO.remove(picture);
		pictureDAO.flush();
	}

	@Transactional
	public void deletePictures(Set<Integer> deletePicturesId) {
		Query query = pictureDAO.createNamedQuery("deletePicturesById", -1, -1);
		query.setParameter(1, deletePicturesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Picture> loadPictures() {
		return pictureDAO.findAllPictures();

	}

	@Transactional
	public Set<Picture> loadReferencePictures(Set<Picture> pictures) {
		Iterator<Picture> picturesIterator = pictures.iterator();
		Set<Picture> referencedPictures = new HashSet<>();
		while (picturesIterator.hasNext()) {
			Picture currentPicture = picturesIterator.next();

		}
		return referencedPictures;
	}

	public Set<Picture> loadPicturesByIdSet(Set<Integer> pictureIdSet) {

		Iterator<Integer> pictureIdIterator = pictureIdSet.iterator();
		Set<Picture> pictureSet = new HashSet<>();
		while (pictureIdIterator.hasNext()) {
			Integer id = pictureIdIterator.next();
			Picture currentPicture = pictureDAO.findPictureById(id);
			pictureSet.add(currentPicture);
		}
		return pictureSet;
	}

	@Transactional
	public List<Picture> findAllPictures(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Picture>(pictureDAO.findAllPictures(startResult, maxRows));
	}

	@Transactional
	public Picture findPictureByPrimaryKey(Integer id) {
		return pictureDAO.findPictureByPrimaryKey(id);
	}

	@Transactional
	public Integer countPictures() {
		return ((Long) pictureDAO.createQuerySingleResult("select count(o) from Picture o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countPictures(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Picture.class);
		return ((Long) pictureDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countPicturesByName(String queryName) {
		Query query = pictureDAO.createNamedQuery("countPicturesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPicturesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Picture.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadPictureObjectReferencedSet(Picture picture) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (picture.getEvent() != null) {

			Set<Integer> eventIds = new HashSet<Integer>();
			eventIds.add(picture.getEvent().getId());
			objectReferencedSetMap.put("eventIds", eventIds);
		}
		if (picture.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(picture.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadPictureClassReferencedSet(Picture picture) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Picture picture, Object obj) {
		if (obj == picture)
			return true;
		if (!(obj instanceof Picture))
			return false;
		Picture comparedPicture = (Picture) obj;
		if (!CheckPropertyEqual(picture.getName(), comparedPicture.getName())) {
			return false;
		}
		if (!CheckPropertyEqual(picture.getPath(), comparedPicture.getPath())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

